package cn.fl.customer.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.cmm.base.framework.utils.EncryptUtil;
import cn.fl.system.service.ISysDictionaryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.ICstCorpRlCompService;
import cn.fl.customer.vo.CstCorpRlCompVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import fl.customer.facade.customer.condition.CstCorpRlCompQueryCondition;
import fl.customer.facade.customer.dto.CstCorpRlCompDTO;

/**
 * @Description: 法人关联企业信息表 控制层
 */
@Controller
@RequestMapping("/customer/cstcorprlcomp")
public class CstCorpRlCompController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CstCorpRlCompController.class);

	/**
	 * CstCorpRlComp 服务层BEAN
	 */
	@Autowired
	private ICstCorpRlCompService cstCorpRlCompService;

	@Autowired
	private ISysDictionaryService sysDictionaryService;

	/**
	 * 详情页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET})
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
		String crcId = request.getParameter("crcId");
		ModelAndView view = new ModelAndView("customer/cstcorprlcomp/cstCorpRlCompDetail");
		view.addObject("crcId", crcId);
		return view;
	}
	/**
	 * 到新增修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String cstId = request.getParameter("cstId");
		String crcId = request.getParameter("crcId");
		ModelAndView view = new ModelAndView("customer/cstcorprlcomp/cstCorpRlCompAdd");
		view.addObject("cstId", cstId);
		view.addObject("crcId", crcId);//修改时使用的关联关系ID
		//企业关联关系
		List<KeyValueVO> rlTypCdList = this.cstCorpRlCompService.searchRlTypCdList();
		view.addObject("searchSelectRlTypCdList", rlTypCdList);
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String cstId = request.getParameter("cstId");
		String isEncrypt=request.getParameter("isEncrypt");

		if(StringUtils.isEmpty(cstId)){
			ListPageVO<CstCorpRlCompVO> listPage = new ListPageVO<CstCorpRlCompVO>(new ArrayList<CstCorpRlCompVO>(), 0);
			return listPage;
		}
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		CstCorpRlCompQueryCondition qc = new CstCorpRlCompQueryCondition();
		List<Long> cstIdList = new ArrayList<>();
		cstIdList.add(Long.valueOf(cstId));
		qc.setCstIdList(cstIdList);
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		page.setCondition(qc);
		//page.setEveryPage(Integer.MAX_VALUE);//最大数据量
		Pager pager = this.cstCorpRlCompService.searchListPage(page);
		String roleIsEncrypt=this.sysDictionaryService.getRoleisEncrypt();

		List<CstCorpRlCompDTO> list = (List<CstCorpRlCompDTO>) pager.getResultList();
		if(!org.springframework.util.StringUtils.isEmpty(list)){
			if (StringUtils.isNotEmpty(isEncrypt) && BaseConstant.IS_YESNO_YES_STR.equals(isEncrypt) && BaseConstant.IS_YESNO_YES_STR.equals(roleIsEncrypt)) {
				for (CstCorpRlCompDTO dto:list ) {
					dto.setTel(EncryptUtil.mobileEncrypt(dto.getTel()));
				}
			}
		}
		ListPageVO<CstCorpRlCompDTO> listPage = new ListPageVO<CstCorpRlCompDTO>(list, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("参数不完整！");
			return result;
		}
		try {
			List<Long> idList = new ArrayList<>();
			idList.add(Long.valueOf(id));
			this.cstCorpRlCompService.removeByIds(idList);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("删除失败");
			logger.error("删除失败!", ex);
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String isEncrypt=request.getParameter("isEncrypt");

		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "获取成功");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("数据主键不能为空！");
			return result;
		}
		
		try {
			CstCorpRlCompVO vo = this.cstCorpRlCompService.selectById(Long.valueOf(id));
			String roleIsEncrypt=this.sysDictionaryService.getRoleisEncrypt();
			if (null == vo) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("数据不存在！");
			} else {
				if (StringUtils.isNotEmpty(isEncrypt) && BaseConstant.IS_YESNO_YES_STR.equals(isEncrypt) && BaseConstant.IS_YESNO_YES_STR.equals(roleIsEncrypt)) {
					vo.setTel(EncryptUtil.mobileEncrypt(vo.getTel()));
				}
			}
			result.setData(vo);
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("获取数据失败！");
			logger.error("获取数据失败！", ex);
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
		try {
			CstCorpRlCompVO entity = this.getRequestParams(request);
			entity.setCrtTm(new Date());
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setIsDel(BaseConstant.IS_YESNO_NO);
			Long id = this.cstCorpRlCompService.add(entity);
			result.setData(id);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("新增失败!");
			logger.error("", ex);
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id"); 
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,"修改成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("数据主键不能为空！");
			return result;
		}
		try {
			CstCorpRlCompVO entity = this.getRequestParams(request);
			entity.setMdfTm(new Date());
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setId(Long.valueOf(Long.valueOf(id)));
			boolean success = this.cstCorpRlCompService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("修改失败！");
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("修改失败!");
			logger.error("修改失败!", ex);
		}
		return result;
	}
	
	
	/**
	 * 获取新增修改参数
	 */
	private CstCorpRlCompVO getRequestParams(HttpServletRequest request) {
		String rlTypCd = request.getParameter("rlTypCd");//企业关系
		String compNm = request.getParameter("compNm");//企业名称
		String corpRep = request.getParameter("corpRep");//法人代表
		String tel = request.getParameter("tel");//手机号或者座机号
		String rlRem = request.getParameter("rlRem");//备注
		String cstId = request.getParameter("cstId");//客户ID
		String addr = request.getParameter("addr");
		
		if(StringUtils.isEmpty(cstId) || !StringUtils.isNumeric(cstId)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请确保客户信息存在后在进行操作!");
		}
		
		if(StringUtils.isEmpty(rlTypCd)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请选择企业关系!");
		}
		
		if(StringUtils.isEmpty(compNm) || compNm.length() > 100 || !StringUtils.isCustomerName(compNm)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "企业名称不能为空,支持格式[艾合买提•倪格提],并且长度不能大于100个字符。");
		}
		
		if(StringUtils.isNotEmpty(tel) && !StringUtils.isMobilePhoneAndFixedPhone(tel)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的联系方式!");
		}
		
		if(StringUtils.isNotEmpty(rlRem) && rlRem.length() > 100){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "备注长度不能超过100个字符!");
		}
		
		CstCorpRlCompVO entity = new CstCorpRlCompVO();
		entity.setCstId(Long.valueOf(cstId));
		entity.setCompNm(compNm);
		entity.setCorpRep(corpRep);
		entity.setRlRem(rlRem);
		entity.setTel(tel);
		entity.setRlTypCd(rlTypCd);
		entity.setAddr(addr);
		entity.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
		entity.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		return entity;
	}
}

